import { useDrop } from "react-dnd";
import { Button, Card, Empty, Form } from "antd";
import styles from "./index.less";
import React, { useCallback, useRef, useLayoutEffect } from "react";
import { FormattedMessage } from "umi";
import { ComponentContainer } from "@/pages/diagnose/generate/Pannel/components/componentContainer";
import { usePanelGeneratorStore } from "@/pages/diagnose/generate/Pannel/store/panelGeneratorStore";


/**
 * panel section container
 * @param {{type: string, isDragging: boolean, acceptItem: string[]}} props 
 * @returns container
 */
function SectionContainer(props) {
    const configStore = usePanelGeneratorStore((state) => state.data)
    const [{ canDrop, isOverCurrent }, drop] = useDrop(() => ({
        accept: props.acceptItem,
        drop(_item, monitor) {
            const didDrop = monitor.didDrop()
            if (didDrop) {
                return
            }
        },
        collect: (monitor) => ({
            isOver: monitor.isOver(),
            isOverCurrent: monitor.isOver({ shallow: true }),
            // canDrop: monitor.canDrop(),
        }),
    }))
    const [display, setDisplay] = React.useState(undefined)
    const containerRef = React.useRef()
    const prev = useRef(null);
    useLayoutEffect(() => {
        if (containerRef.current) {
            let currentContainerRef = props.type === 'taskform' ? containerRef.current.children[0] : containerRef.current.children
            if (prev.current === null || prev.current === undefined) {
                // mounted保留前状态
                prev.current = Array.from(currentContainerRef).map((item, index) => {
                    const rect = item.getBoundingClientRect();
                    return { dom: item, pos: { left: rect.left, top: rect.top } };
                });
            } else {
                prev.current.map(({ dom, pos }) => {
                    // 获取新状态
                    const rect = dom.getBoundingClientRect();
                    // invent 还原到初始状态
                    dom.style = `transform: translate(${pos.left - rect.left}px, ${pos.top - rect.top
                        }px); grid-column: span ${props.type === 'taskform' ? 1 : 3}`;
                    // play: 执行动画
                    dom.animate(
                        [
                            {
                                transform: `translate(${pos.left - rect.left}px, ${pos.top - rect.top
                                    }px)`,
                            },
                            {
                                transform: "translate(0,0)",
                            },
                        ],
                        {
                            duration: 300,
                            easing: "cubic-bezier(0,0,0.32,1)",
                            fill: "forwards",
                        }
                    );
                });
                prev.current = Array.from(currentContainerRef).map((item, index) => {
                    const rect = item.getBoundingClientRect();
                    return { dom: item, pos: { left: rect.left, top: rect.top } };
                });
            }
        }
    }, [configStore]);
    const onHover = (index) => {
        setDisplay(index)
    }
    const onLeave = () => {
        setDisplay(undefined)
    }
    const savePrev = useCallback(new Promise((resolve, reject) => {
        if (containerRef.current !== null && containerRef.current !== undefined) {
            let currentContainerRef = props.type === 'taskform' ? containerRef.current.children[0] : containerRef.current.children
            prev.current = Array.from(currentContainerRef).map((item, index) => {
                const rect = item.getBoundingClientRect();
                return { dom: item, pos: { left: rect.left, top: rect.top } };
            });
        }
        resolve(prev)
    }), [configStore])
    const renderComponent = useCallback((config, index) => {
        if (config !== undefined) {
            return (
                <div className={styles.item} onMouseEnter={() => onHover(index)} onMouseLeave={onLeave}
                    key={index} style={{ gridColumn: `span ${props.type === 'taskform' ? 1 : 3}` }}>
                    <ComponentContainer value={config} displayIndex={display} index={index} savePrev={savePrev} />
                </div>
            )
        }
    }, [configStore, display])

    const dropTypeSwitch = useCallback((type) => {
        if (type === 'taskform' && configStore?.taskform?.length !== 0) {
            return (
                <div ref={containerRef}>
                    <Form className={styles.itemGrid}>
                        {
                            configStore.taskform?.map((value, index) => renderComponent(value, index))
                        }
                        <div className="mockButton" style={{ margin: 0, display: 'flex', alignItems: 'center', gap:'10px' }}>
                            <Button type='primary' style={{ marginRight: '.6rem' }}><FormattedMessage id="pages.diagnose.startdiagnosis" defaultMessage="开始诊断" /></Button>
                            <Button type='primary'><FormattedMessage id="pages.diagnose.importdiagnosisresultsoffline" defaultMessage="离线导入" /></Button>
                        </div>
                    </Form>
                </div>
            )
        } else if (type === 'panels' && configStore?.pannels?.length !== 0) {
            return (
                <div ref={containerRef} className={styles.itemGrid}>
                    {
                        configStore.pannels?.map((value, index) => renderComponent(value, index))
                    }
                </div>
            )
        } else {
            return (
                <>
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description={<span><FormattedMessage id="pages.diagnose.generatePanel.noComponent" defaultMessage="暂时没有组件，从左边拖入试试吧" /></span>} />
                </>
            )
        }
    }, [configStore, display])

    return (
        <Card style={{ zIndex: 0 }} size="small" ref={drop} className={styles.sectionContainer}>
            <div className={`${styles.dropIndicator} ${props.isDragging ? styles.dragging : ''} ${canDrop ? styles.canDrop : ''} ${isOverCurrent ? canDrop ? styles.cannot : styles.hovering : ''}`}>
            </div>
            {
                dropTypeSwitch(props.type)
            }
        </Card>
    );
}

export default SectionContainer;
